<template>
  <div class="login-container">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">健康管理系统</h3>
        <p class="subtitle">普通用户登录</p>
      </div>

      <el-form-item prop="phone">
        <el-input
          ref="phoneInputRef"
          v-model="loginForm.phone"
          placeholder="手机号"
          name="phone"
          type="text"
          tabindex="1"
          auto-complete="on"
          maxlength="11"
        >
          <template #prefix>
            <svg-icon icon-class="phone" />
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <div class="code-input-container">
          <el-input
            v-model="loginForm.code"
            placeholder="验证码"
            name="code"
            type="text"
            tabindex="2"
            maxlength="6"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <svg-icon icon-class="message" />
            </template>
          </el-input>
          <el-button
            class="code-btn"
            :disabled="countdown > 0"
            @click="getCode"
          >
            {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.prevent="handleLogin"
      >
        登录
      </el-button>

      <div class="login-switch">
        <span>管理员登录？</span>
        <el-link type="primary" @click="switchToAdminLogin">点击切换</el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { validPhone } from '@/utils/validate'

const router = useRouter()
const userStore = useUserStore()

const loginForm = reactive({
  phone: '',
  code: ''
})

const loginRules = {
  phone: [
    { required: true, trigger: 'blur', message: '请输入手机号' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  code: [
    { required: true, trigger: 'blur', message: '请输入验证码' },
    { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

const loading = ref(false)
const countdown = ref(0)
const loginFormRef = ref<any>(null)
const phoneInputRef = ref<any>(null)

// 验证手机号
function validatePhone(rule: any, value: string, callback: any) {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!validPhone(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

// 获取验证码
const getCode = async () => {
  // 直接从响应式对象获取手机号
  const phone = loginForm.phone
  
  if (!phone) {
    ElMessage.error('请输入手机号')
    return
  }
  
  if (!validPhone(phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  
  try {
    // 修复：传递正确的参数格式给后端
    const result = await userStore.getVerificationCode(phone)
    if (result && result.success) {
      ElMessage.success('验证码发送成功')
      startCountdown()
    } else {
      ElMessage.error(result?.message || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('验证码发送失败')
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    // 修复：传递正确的参数给登录方法
    const result = await userStore.phoneLogin(loginForm.phone, loginForm.code)
    
    if (result && result.success) {
      ElMessage.success('登录成功')
      router.push('/app/profile')
    } else {
      ElMessage.error(result?.message || '登录失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 切换到管理员登录
const switchToAdminLogin = () => {
  router.push('/login')
}

onMounted(() => {
  setTimeout(() => {
    if (phoneInputRef.value) {
      phoneInputRef.value.focus()
    }
  }, 100)
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-form {
    width: 400px;
    max-width: 100%;
    padding: 35px 35px 15px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .title-container {
      position: relative;
      text-align: center;
      margin-bottom: 30px;

      .title {
        font-size: 26px;
        color: #409eff;
        margin: 0 auto 20px;
        font-weight: bold;
      }

      .subtitle {
        font-size: 14px;
        color: #909399;
        margin: 0;
      }
    }

    .code-input-container {
      display: flex;
      gap: 10px;

      .el-input {
        flex: 1;
      }

      .code-btn {
        width: 120px;
        flex-shrink: 0;
      }
    }

    .login-switch {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #909399;

      .el-link {
        margin-left: 5px;
      }
    }
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>